package com.example.presentshopping.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.StringUtils
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.base.MyApplication
import com.example.presentshopping.config.base.MyApplication.getContext
import com.example.presentshopping.config.bean.LuckydrawBean
import com.example.presentshopping.config.bean.NoticeBean
import com.example.presentshopping.config.bean.OpenTokenBean
import com.example.presentshopping.config.bean.VersionBaen
import com.example.presentshopping.exent.ImageVIewExent
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.http.HttpURL.Req_notice
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.dialog.MessageDialog
import com.example.presentshopping.ui.dialog.UpDateDialog
import com.example.presentshopping.ui.fragment.*
import com.example.presentshopping.utils.HProgressDialogUtils
import com.example.presentshopping.utils.edit.StatusBarUtil
import com.example.presentshopping.utils.sign.CheckRandomNumber
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.IntentJumpUtils
import com.example.presentshopping.utils.tool.LogUtils
import com.example.presentshopping.utils.tool.SoftHideKeyBoardUtil
import com.permissionx.guolindev.PermissionX
import com.qiniu.android.storage.UploadManager
import com.soundcloud.android.crop.Crop
import com.tencent.bugly.Bugly
import com.xuexiang.xupdate.XUpdate
import com.xuexiang.xupdate._XUpdate
import com.xuexiang.xupdate.service.OnFileDownloadListener
import com.xuexiang.xutil.app.PathUtils
import com.xuexiang.xutil.file.FileUtils
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.io.File
import java.util.*

class MainActivity : BaseMvpActivity() {

    private var showFragmentPage = -1
    private var fragmentTransaction: FragmentTransaction? = null
    private lateinit var TabFragment1: Fragment
    private lateinit var TabFragment2: Fragment
    private lateinit var TabFragment3: Fragment
    private lateinit var TabFragment4: Fragment
    var versionBaen: VersionBaen? = null
    var sendMesPresenter: PublicPresenter? = null
    var announPresenter: PublicPresenter? = null
    var MesPresenter: PublicPresenter? = null
    private val REQUEST_CODE_SELECT_APK_FILE = 1000

    var openToken: OpenTokenBean? = null
    var noticeBean: NoticeBean? = null


    override val layoutId: Int
        get() = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        /**
         * 设置状态栏透明：侵入式透明status bar >> 顶部需要沉浸的是图片View.
         * 不要忘记了, 在当前activity onCreate中设置 取消padding,  因为这个padding 我们用代码实现了,不需要系统帮我
         */
        StatusBarUtil.setRootViewFitsSystemWindows(this, false)
        SoftHideKeyBoardUtil.assistActivity(this)
        initFramgment()
        Bugly.init(applicationContext, "7023a70483", false);

        sendMesPresenter = PublicPresenter(this, false, "")
        sendMesPresenter?.attachView(this)

        MesPresenter = PublicPresenter(this, false, "")
        MesPresenter?.attachView(this)
        announPresenter = PublicPresenter(this, false, "")
        announPresenter?.attachView(this)
        if (IntentJumpUtils.isLogin()) {
            // 跳转首页
            seniority()

        } else {
            // 登录

        }

        getAppUpdate()
        ly_Tab1.setOnClickListener {                   // 加载Fragment
            switchFragment(0)
        }
        ly_Tab2.setOnClickListener {                      // 加载Fragment
            switchFragment(1)
        }
        ly_Tab3.setOnClickListener {                      // 加载Fragment
            switchFragment(2)
        }
        ly_Tab4.setOnClickListener {
            if (IntentJumpUtils.isLogin()) {
                // 跳转首页
                switchFragment(3)
            } else {
                // 登录
                IntentJumpUtils.goToLogin(this@MainActivity, "")
            }
            // 加载Fragment

        }


    }

    fun seniority() {
        sendMesPresenter?.netWorkRequestPost(HttpURL.Req_checkTodayOrder,
            HttpRequest.getGoodsDetail(
                ""
            ),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    Log.e("MainActivity", "" + JSONObject(data).get("data"))
                    if (JSONObject(data).get("data") == 2) {
                        onMesins()
                    }


                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })

    }

    fun onMesins() {
        MessageDialog.Builder(this)
            .setTitle("")
            .setTvTitle("")
            .setMessage("亲！您今日的任务还未完成哟！赶紧下单参与拼团吧!")
            .setConfirm("确定")
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: Dialog?) {
                    context?.startActivity(Intent(context, SpellgroupActivity().javaClass))
                }

                override fun onCancel(dialog: Dialog?) {

                }
            }).show()
    }

    override fun onDestroy() {
        sendMesPresenter?.detachView()
        MesPresenter?.detachView()
        super.onDestroy()
    }

    override fun onStart() {
        super.onStart()
        setPermission()
        MyApplication.bitmapList.clear()
        announcement()
        setBalis()
    }

    companion object {
        // 跳转到当前页面。
        fun toStartActivity(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent)
        }
    }

    override fun showToast(msg: String?) {

    }

    override fun onSuccess(data: String?) {

    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    fun initFramgment() {
        // 初始化Fragment。
        TabFragment1 = HomeFragment()
        TabFragment2 = BoardFragment()
        TabFragment3 = ClientFragment()
        TabFragment4 = MyFragment()
        /**
         * getFragmentManager();注：如果使用Android3.0以下的版本，需要引入v4的包，
         * 然后Activity继承FragmentActivity，然后通过getSupportFragmentManager获得FragmentManager。
         */
        // 开启一个Fragment事务
        fragmentTransaction = supportFragmentManager.beginTransaction()

        // 如果MessageFragment为空，则创建一个并添加到界面上
        fragmentTransaction!!.add(R.id.id_content, TabFragment1 as HomeFragment)
        fragmentTransaction!!.add(R.id.id_content, TabFragment2 as BoardFragment)
        fragmentTransaction!!.add(R.id.id_content, TabFragment3 as ClientFragment)
        fragmentTransaction!!.add(R.id.id_content, TabFragment4 as MyFragment)
        // 重置按钮
        resetBtn()
        // 加载Fragment
        fragmentTransaction!!.commit()


        // 页面判断（初始化加载页面）
        switchFragment(0)
    }

    // 加载Fragment
    fun switchFragment(page: Int) {
        if (page == showFragmentPage) {
            return
        }
        fragmentTransaction = supportFragmentManager.beginTransaction()
        resetBtn()
        // 页面判断
        when (page) {
            0 -> {
                ivTab1.setImageResource(R.drawable.ic_shouye)
                tvTab1.setTextColor(resources.getColor(R.color.colorMain))
                // 设置要显示的Fragment
                fragmentTransaction!!.show(TabFragment1!!)
            }
            1 -> {
                iv_Tab2.setImageResource(R.drawable.ic_fenlei)
                tv_Tab2.setTextColor(resources.getColor(R.color.colorMain))
                // 设置要显示的Fragment
                fragmentTransaction!!.show(TabFragment2!!)
            }
            2 -> {
                iv_Tab3.setImageResource(R.drawable.ic_gouwuche)
                tv_Tab3.setTextColor(resources.getColor(R.color.colorMain))
                // 设置要显示的Fragment
                fragmentTransaction!!.show(TabFragment3!!)
            }
            3 -> {
                iv_Tab4.setImageResource(R.drawable.ic_gerenzhongxin)
                tv_Tab4.setTextColor(resources.getColor(R.color.colorMain))
                // 设置要显示的Fragment
                fragmentTransaction!!.show(TabFragment4!!)
            }
        }

//        // 发送到Fragment页面刷新数据
//        EventBus.getDefault().post(MainFragmentEvent(page))

        // 加载Fragment
        // 加载Fragment
        fragmentTransaction!!.commit()
        showFragmentPage = page

    }

    fun resetBtn() {

        ivTab1.setImageResource(R.drawable.ic_shouye1)
        tvTab1.setTextColor(resources.getColor(R.color.colorLineBox))

        iv_Tab2.setImageResource(R.drawable.ic_fenlei1)
        tv_Tab2.setTextColor(resources.getColor(R.color.colorLineBox))

        iv_Tab3.setImageResource(R.drawable.ic_gouwuche1)
        tv_Tab3.setTextColor(resources.getColor(R.color.colorLineBox))

        iv_Tab4.setImageResource(R.drawable.ic_gerenzhongxin1)
        tv_Tab4.setTextColor(resources.getColor(R.color.colorLineBox))

        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        fragmentTransaction!!.hide(TabFragment1)
        fragmentTransaction!!.hide(TabFragment2)
        fragmentTransaction!!.hide(TabFragment3)
        fragmentTransaction!!.hide(TabFragment4)

    }

    //检查所有需要的权限
    fun setPermission() {
        PermissionX.init(this)
            .permissions(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            .onExplainRequestReason { scope, deniedList ->
                val message = "PermissionX需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {

                } else {

                }
            }
    }

    /**
     * 获取版本更新URL
     */
    fun getAppUpdate() {
        MesPresenter?.setHaveCode(false)
        MesPresenter?.netWorkRequestPost(
            HttpURL.Req_getVersion,
            HttpRequest.getGoodsDetail(""),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    Log.e("MesPresenter", data.toString())
                    versionBaen = GsonUtils.getGson().fromJson(data, VersionBaen().javaClass)
                    // 版本号
                    val versionCode: Int = versionBaen?.version_code?.toInt()!!
                    Log.e("getAppUpdate", "" + AppUtils.getAppVersionCode())
                    Log.e("getAppUpdate", "" + versionCode)
                    if (!TextUtils.isEmpty(versionBaen?.down_url) && versionCode > AppUtils.getAppVersionCode()) {
                        /** 检查更新  */
                        checkUpDate(
                            versionBaen?.coerce_upgrade.toString(),
                            versionBaen?.down_url,
                            versionBaen?.remark
                        )
                        Log.e("getAppUpdate", "" + "checkUpDate")
                    }
                }


                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }


    fun checkUpDate(isUpdate: String?, downloadUrl: String?, description: String?) {
        if ((StringUtils.equals(isUpdate, "1") || StringUtils.equals(isUpdate, "2"
            )) && !TextUtils.isEmpty(downloadUrl)
        ) {
            Log.e("MesPresenter", downloadUrl.toString())
            val upDateDialog = UpDateDialog(context, isUpdate)
            upDateDialog.setContent(description, "", object : UpDateDialog.OnBtnClickListener {
                override fun onConfirmClick(upDateDialog: UpDateDialog?) {
                    if (downloadUrl.toString().contains("http")) {
                        XUpdate.newBuild(this@MainActivity)
                            .apkCacheDir(PathUtils.getExtDownloadsPath()) //设置下载缓存的根目录
                            .build()
                            .download(downloadUrl, object : OnFileDownloadListener {
                                //设置下载的地址和下载的监听
                                override fun onStart() {
                                    HProgressDialogUtils.showHorizontalProgressDialog(context,
                                        "下载进度",
                                        false)
                                }

                                override fun onProgress(progress: Float, total: Long) {
                                    HProgressDialogUtils.setProgress(Math.round(progress * 100))
                                }

                                override fun onCompleted(file: File): Boolean {
                                    HProgressDialogUtils.cancel()
                                    AppUtils.installApp(file)
                                    return false
                                }

                                override fun onError(throwable: Throwable?) {
                                    HProgressDialogUtils.cancel()
                                }
                            })

                    } else {
                    }
                }

                override fun onCancelClick(upDateDialog: UpDateDialog?) {

                }
            })
            upDateDialog?.show()
        }
    }

    //相机拍摄的头像文件(存放在SD卡根目录下) 当前时间+.jpg方式
    private val IMAGE_FILE_NAME = "image_file_name.jpg"
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.i("requestCode", "requestCode" + requestCode)
        when (requestCode) {
            Crop.REQUEST_CROP -> if (resultCode == RESULT_OK) {

                //裁剪图片uri
                val cropImageUri = Crop.getOutput(data)
                LogUtils.e("裁剪图片", "裁剪成功    图片地址=" + cropImageUri.path)
                openToken(cropImageUri.path)


            }
            REQUEST_CODE_SELECT_APK_FILE -> {
                _XUpdate.startInstallApk(getContext(),
                    FileUtils.getFileByPath(PathUtils.getFilePathByUri(context,
                        data!!.data))!!)

            }


            else -> {
            }
        }
    }

    fun openToken(url: String?) {
        sendMesPresenter?.netWorkRequestGet(HttpURL.Req_openToken, object : TaskCallback {
            override fun onSuccess(data: String?) {
                openToken = GsonUtils.getGson().fromJson(data, OpenTokenBean().javaClass)
                osuang(openToken?.data?.list, url)

            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {

            }

        })

    }

    //    String key = <指定七牛服务上的文件名，或 null>;
//    String token = <从服务端SDK获取>;
    fun osuang(token: String?, date: String?) {
        val uploadManager = UploadManager()

        val kay = CheckRandomNumber.string(16)
        uploadManager.put(File(date), kay, token,
            { key, info, response ->
                if (info.isOK) {
                    Log.e("osuang", key)
                    Log.e("osuang", response.toString())
                    val url = "https://wmoss.lxtianxia.cn/$key"
                    UserInfo(url)
                }

            }, null)

    }

    fun UserInfo(url: String) {
        sendMesPresenter?.netWorkRequestPost(HttpURL.Req_editUserInfo,
            HttpRequest.editUserInfo(url),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    val exne = ImageVIewExent()
                    exne.url = "cropImageUri.path"
                    EventBus.getDefault().post(exne)

                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }


    /**
     * 检查SD卡是否可用
     */
    private fun hasSdcard(): Boolean {
        val state = Environment.getExternalStorageState()
        //有存储的sdcard
        return state == Environment.MEDIA_MOUNTED
    }

    fun setBalis() {
        sendMesPresenter?.netWorkRequestGet(HttpURL.Req_getTurntableList,
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    val luckydrawBean = GsonUtils.getGson().fromJson(data,
                        LuckydrawBean::class.java)
                    for (sin in luckydrawBean.data) {
                        HttpRequest.getNetBitmap(sin.img, context)
                    }


                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }
            })
    }


    fun announcement() {
        announPresenter?.setHaveCode(false)
        announPresenter?.netWorkRequestGet(Req_notice, object : TaskCallback {
            override fun onSuccess(data: String?) {
                noticeBean = GsonUtils.getGson().fromJson(data, NoticeBean().javaClass)
                val jsn = JSONObject(data)
                val jsondata = jsn.getJSONObject("data")

                Log.e("announcement", jsondata.getString("is_notice"))
                if (jsondata.getString("is_notice").contains("1")) {
                    var dialog = AlertDialog.Builder(this@MainActivity)
                        .setTitle("系统公告")
                        .setMessage(jsondata.getString("notice_explain"))
                        .setNegativeButton("确定") { _, _ ->
                            val i = Intent(Intent.ACTION_MAIN)
                            i.addCategory(Intent.CATEGORY_HOME)
                            startActivity(i)

                        }.setCancelable(false)
                        .create().show()
                }

            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {

            }

        })

    }

}




